<template>
    <el-card>
        <template #header>
            <!-- 按钮新增 -->
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addTrademark">添加</el-button>
        </template>
        <!-- 表格区域 -->
        <el-table border :data="pageData">
            <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>
            <el-table-column label="品牌名称" prop="tmName"></el-table-column>
            <el-table-column label="品牌LOGO" align="center">
                <template #default="{ row, $index }">
                    <img :src="row.logoUrl" alt="" style="{width:50px;height:80px;}">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row, $index }">
                    <el-button type="primary" size="small" @click="editTrademark(row)"
                        icon="el-icon-edit-outline">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteTrademark(row)"
                        icon="el-icon-delete-solid">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
            :page-sizes="[3, 6, 9]" :page-size="limit" layout="prev, pager, next, jumper , -> , sizes , total" :total="total">
        </el-pagination>

        <!-- 新增品牌的dialog -->
        <el-dialog title="新增品牌" :visible.sync="dialogFormVisible" top="0px">
            <el-form style="width:500px" :model="form" :rules="rules" ref="ruleForm">
                <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                    <el-input v-model="form.tmName"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                    <!-- 用户头像上传 -->
                    <el-upload :action="action" :show-file-list="false" :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm('ruleForm')">取 消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
            </div>
        </el-dialog>

    </el-card>
</template>

<script>
import trademarkApi from '@/api/trademark'
import { cloneDeep } from 'lodash'
export default {
    name: "VTrademark",
    data() {
        return {
            page: 1,   //当前第几页
            limit: 3,  //每页多少条
            total: 0,   //总共多少条
            pageData: [],  //表格数据
            dialogFormVisible: false,   //新增品牌控制
            form: {
                tmName: '', //品牌名称
                logoUrl: ''      //品牌logo
            },
            action: `${process.env.VUE_APP_BASE_API}/admin/product/upload`,
            // 表单验证
            rules: {
                tmName: [
                    { required: true, message: '请输入品牌名', trigger: 'blur' },
                    { min: 3, max: 5, message: '品牌名应该3-5个字符', trigger: 'blur' },
                ],
                logoUrl: [{ required: true, message: '请插入图片', trigger: 'blur' }]
            }
        }
    },
    methods: {
        //编辑品牌
        editTrademark(row) {
            //显示弹框
            this.dialogFormVisible = true
            //数据回显
            this.form = cloneDeep(row)
        },
        //删除品牌
        deleteTrademark(row) {
            this.$confirm(`是否删除${row.tmName}?`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                //点确认回调
                await trademarkApi.deleteTrademark(row.id)
                this.getPage()
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //提交表单
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.dialogFormVisible = false
                    try {
                        await trademarkApi.save(this.form)
                        this.$message.success('保存成功')
                        this.getPage()
                    } catch (error) {
                        this.$message.danger('保存失败')
                    }

                }
            });
        },
        //重置表单
        resetForm(formName) {
            this.dialogFormVisible = false
            this.$refs[formName].resetFields()
        },
        //上传成功的回调
        handleAvatarSuccess(res, file) {
            // console.log(res);
            this.form.logoUrl = res.data
        },
        //上传之前的回调
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        //新增品牌
        addTrademark() {
            //清空表单
            this.form = {
                tmNmae: '', logoUrl: ''
            }
            this.dialogFormVisible = true
        },
        //每页几条的变化回调
        handleSizeChange(val) {
            this.limit = val
            this.getPage()
        },
        //当前第几页的变化回调
        handleCurrentChange(val) {
            this.page = val
            this.getPage()
        },
        //获取表格初始数据
        async getPage() {
            let res = await trademarkApi.reqGetPage(this.page, this.limit)
            this.pageData = res.data.records
            this.total = res.data.total
        }
    },
    mounted() {
        this.getPage()
    }
}
</script>

<style  scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>